package com.masterclient.app.modules.order.activity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.alipay.sdk.app.PayTask;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselib.utils.status.StatusBarUtils;
import com.eoner.baselibrary.bean.address.AddressBean;
import com.eoner.baselibrary.bean.address.AddressMessage;
import com.eoner.baselibrary.bean.goods.CouponMessage;
import com.eoner.baselibrary.bean.order.ConfirmOrderCoupons;
import com.eoner.baselibrary.bean.order.ConfirmOrderData;
import com.eoner.baselibrary.bean.order.ConfirmOrderOrder;
import com.eoner.baselibrary.bean.order.ConfirmOrderPrice;
import com.eoner.baselibrary.bean.order.CreateOrderData;
import com.eoner.baselibrary.bean.order.CustomsClearanceMessage;
import com.eoner.baselibrary.bean.order.PayResult;
import com.eoner.baselibrary.bean.order.RefreshOrderData;
import com.eoner.baselibrary.bean.order.TradeStatusData;
import com.eoner.baselibrary.bean.pay.PayParam;
import com.eoner.baselibrary.utils.DoubleClickUtil;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselibrary.utils.UtilCollection;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.MainViewHolder;
import com.masterclient.app.businessmodule.minemodule.address.AddNewAddressActivity;
import com.masterclient.app.businessmodule.minemodule.address.ChangeAddressActivity;
import com.masterclient.app.businessmodule.settingmodule.crossborder.CrossBorderNameSelectActivity;
import com.masterclient.app.businessmodule.settingmodule.crossborder.model.CrossBorderUserMessage;
import com.masterclient.app.modules.bridge.BridgeActivity;
import com.masterclient.app.modules.order.CouponChooseActivity;
import com.masterclient.app.modules.order.CustomerOrderActivity;
import com.masterclient.app.modules.order.PaySuccessActivity;
import com.masterclient.app.modules.order.PickGoodsAddressDialog;
import com.masterclient.app.modules.order.adapter.SubmitOrderAddressAdapter;
import com.masterclient.app.modules.order.adapter.SubmitOrderCouponAdapter;
import com.masterclient.app.modules.order.adapter.SubmitOrderCrossBorderAdapter;
import com.masterclient.app.modules.order.adapter.SubmitOrderCrossBorderAgreementAdapter;
import com.masterclient.app.modules.order.adapter.SubmitOrderOtherInfoAdapter;
import com.masterclient.app.modules.order.adapter.SubmitOrderPayAdapter;
import com.masterclient.app.modules.order.adapter.SubmitOrderProductsAdapter;
import com.masterclient.app.modules.order.contract.SubmitOrderContract;
import com.masterclient.app.modules.order.contract.SubmitOrderPresenter;
import com.masterclient.app.modules.order.utils.ModelAdapterUtil;
import com.masterclient.app.widget.TitlebarView;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

import static com.masterclient.app.App.context;
import static com.masterclient.app.modules.order.InvoiceActivity.RESULT_CODE;

@Route(path = AroutePath.ORDER_SUBMIT_ACTIVITY)
public class SubmitOrderActivity extends BaseActivity<SubmitOrderPresenter> implements SubmitOrderContract.View {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.title_view)
    TitlebarView title_view;
    @BindView(R.id.tv_actual_price)
    TextView tvActualPrice;

    @BindView(R.id.cross_border_agreement_layout)
    View cross_border_agreement_layout;
    @BindView(R.id.cross_border_agreement_txt)
    View cross_border_agreement_txt;
    @BindView(R.id.cross_border_agreement_layout_item)
    View cross_border_agreement_layout_item;
    @BindView(R.id.cross_border_agreement_checkbox)
    CheckBox cross_border_agreement_checkbox;
    @BindView(R.id.submit_order_btn)
    TextView submitOrderBtn;
    @BindView(R.id.tv_top_tip)
    TextView tvTopTip;
    @BindView(R.id.tv_bg)
    TextView tvBg;

    @Autowired(name = "id")
    String id;

    final List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    DelegateAdapter delegateAdapter;

    SubmitOrderAddressAdapter adapter_address;
    SubmitOrderCrossBorderAdapter adapter_cross_border;
    SubmitOrderCrossBorderAgreementAdapter adapter_cross_border_agreement;
    SubmitOrderCouponAdapter adapter_coupon;
    SubmitOrderPayAdapter adapter_pay;
//    SubmitCustodyAdapter adapter_custody;
    SubmitOrderProductsAdapter adapter_products;
    SubmitOrderOtherInfoAdapter adapter_other_info;

    String address_id = "0", customs_clearance_id = "0", customs_clearance_agreement, payment_id = "0", bupiao = "0", balance = "0", gold = "0", buy_type = "2";
    String coupon_id = "0", live_room_id = "0", remark, invoice;
    String buy_product;
    String address_desc = "";
    String charge_account = "";
    String saleType = "";
    String relationOrderId = "";//区分是代发单
    String isCustody = "0";
    String freightType = "0";
    boolean firstShowCustodyDialog = true;

    IWXAPI iwxapi;
    RxBus rxBus;
    private static final int SDK_PAY_FLAG = 1;
    private String clickBtnName = "";

    String convert, trade_no;

    private boolean isGiving = false; //是否用赠送品

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_submit_activity);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        StatusBarUtils.immersive(getActivity());
        StatusBarUtils.setPaddingSmart(mContext, title_view);

        init();
        add_listener();
        //TODO:判断是否是赠送品
        if (data == null) {
            mPresenter.confirm_order(buy_product, buy_type, charge_account,saleType,relationOrderId,isCustody);
        } else {
            isGiving = mPresenter.checkIsGiving(data);
            display_ui();
        }
    }

    private void init() {
        Utils.setDin(tvActualPrice, this);
        Bundle bundle = getIntent().getExtras();

        buy_type = bundle.getString("buy_type");
        live_room_id = bundle.getString("live_room_id");
        charge_account = bundle.getString("charge_account");
        buy_product = bundle.getString("buy_product");
        saleType = bundle.getString("saleType");
        relationOrderId = bundle.getString("relation_order_id");
        isCustody = bundle.getString("is_custody");
        firstShowCustodyDialog = bundle.getBoolean("first_show_custody_dialog",true);
        data = (ConfirmOrderData) bundle.getSerializable("confirm_order_data");
        if (TextUtils.isEmpty(buy_type)) {
            buy_type = "2";
        }

        if (!TextUtils.isEmpty(saleType)&&"4".equals(saleType)){
            title_view.setTitle("确认采购单");
            tvActualPrice.setTextColor(Color.parseColor("#FF5000"));
            submitOrderBtn.setText(!TextUtils.isEmpty(isCustody)&&"1".equals(isCustody)?"提交保管":"提交采购");
            submitOrderBtn.setBackgroundResource(R.drawable.shape_gradient_ffb049_ff5000);
            if (isCustody.equals("1")){
                tvBg.setVisibility(View.VISIBLE);
            }
        }

        if (!TextUtils.isEmpty(saleType)&&"6".equals(saleType)){
            title_view.setTitle(TextUtils.isEmpty(relationOrderId)?"确认提货单":"确认代发单");
            tvActualPrice.setTextColor(Color.parseColor("#FF5000"));
            submitOrderBtn.setText("提交");
            submitOrderBtn.setBackgroundResource(R.drawable.shape_gradient_ffb049_ff5000);
            freightType = "1";
        }

        convert = getIntent().getStringExtra("convert");

        iwxapi = WXAPIFactory.createWXAPI(mContext, null);
        rxBus = RxBus.$();
        rxBus.OnEvent(rxBus.register(Config.PAY_RESULT), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                String result = (String) o;
                switch (result) {
                    case Config.PAY_SUCCESS://支付成功
                        payOrderSuccess();
                        break;
                    case Config.PAY_FAILED://支付失败
                        payOrderFailure();
                        break;
                }
            }
        });

        rxBus.OnEvent(rxBus.register(Config.CROSS_BORDER_OPERATE), new Consumer<Object>() {
            @Override
            public void accept(@NonNull Object o) throws Exception {
                String temp = (String) o;
                if (customs_clearance_id.equals(temp)) {
                    customs_clearance_id = "0";
                    refreshOrderMessage();
                    data.setCustoms_clearance(null);
                    adapter_cross_border.notifyDataSetChanged();
                }

            }
        });

        VirtualLayoutManager layoutManager = new VirtualLayoutManager(mContext);
        layoutManager.setInitialPrefetchItemCount(10);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemViewCacheSize(16);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        recyclerView.setRecycledViewPool(viewPool);
        for (int i = 0; i < 13; i++) {
            viewPool.setMaxRecycledViews(i, 10);
        }
        delegateAdapter = new DelegateAdapter(layoutManager, false);
        recyclerView.setAdapter(delegateAdapter);

    }


    private void add_listener() {

        title_view.setOnViewClick(new TitlebarView.onViewClick() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });

    }

    @OnClick({R.id.submit_order_btn})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.submit_order_btn:
                if (data == null) {
                    return;
                }
                if (data.isHas_cross_seller() && !"1".equals(customs_clearance_agreement)) {
                    showToast("请同意并接受用户购买须知");
                    return;
                }

                if (Float.valueOf(confirmOrderPrice.getPay_price()) > 0) {
                    if ("0".equals(payment_id)) {
                        //没有选择支付方式
                        showToast("请至少选择一种付款方式");
                    } else if ("1".equals(payment_id)) {
                        //支付宝支付
                        Uri uri = Uri.parse("alipays://platformapi/startApp");
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
                        if (componentName != null) {
                            showNoticeDialog();
                        } else {
                            showToast("检测到当前设备没有安装支付宝");
                        }
                    } else if ("2".equals(payment_id)) {
                        //微信支付
                        if (iwxapi.isWXAppInstalled()) {
                            showNoticeDialog();
                        } else {
                            showToast("检测到当前设备没有安装微信");
                        }
                    }
                } else {
                    showNoticeDialog();
                }

                break;
        }
    }

    private void showNoticeDialog() {
        if ("6".equals(saleType)&&TextUtils.isEmpty(relationOrderId)){
            long num = 0;
            for (ConfirmOrderOrder bean : data.getOrders()) {
                num += Long.parseLong(TextUtils.isEmpty(bean.getNum())?"0":bean.getNum());
            }
            new PickGoodsAddressDialog(this, String.valueOf(num),data.getAddress(), new PickGoodsAddressDialog.OnConfirmListener() {
                @Override
                public void onConfirm() {
                    generateOrder();
                }
            }).show();
        }else {
            if (TextUtils.isEmpty(data.getPayment_notice())) {
                generateOrder();
            } else {
                ConfirmDialog confirmDialog = new ConfirmDialog(mContext, data.getPayment_notice(), "取消", "继续支付");
                confirmDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                    @Override
                    public void cancel() {
                        confirmDialog.dismiss();
                    }

                    @Override
                    public void confirm() {
                        generateOrder();
                        confirmDialog.dismiss();
                    }
                });
                confirmDialog.show();
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    ConfirmOrderData data;
    ConfirmOrderCoupons confirmOrderCoupons;
    ConfirmOrderPrice confirmOrderPrice;

    @Override
    public void confirm_order_success(ConfirmOrderData data) {
        this.data = data;
        //TODO:判断是否是赠送品
        isGiving = mPresenter.checkIsGiving(data);
        display_ui();
    }

    private void display_ui() {
        if (data != null) {
            this.confirmOrderCoupons = data.getCoupons();
            this.confirmOrderPrice = data.getPrice();
        }
        if (!TextUtils.isEmpty(data.getTop_tips())) {
            tvTopTip.setVisibility(View.VISIBLE);
            tvTopTip.setText(data.getTop_tips());
            FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) recyclerView.getLayoutParams();
            lp.topMargin = ScreenUtils.dp2px(44);
            recyclerView.setLayoutParams(lp);
        } else {
            tvTopTip.setVisibility(View.GONE);
        }
        tvActualPrice.setText("¥ " + data.getPrice().getPay_price());
        adapters.clear();
        delegateAdapter.setAdapters(adapters);
        recyclerView.setAdapter(delegateAdapter);


        //地址
        boolean hasAddress = "0".equals(data.getIs_hidden_address());
        if (adapters.contains(adapter_address)) {
            adapters.remove(adapter_address);
        }
        if (hasAddress) {
            AddressMessage addressMessage = data.getAddress();
            if (addressMessage != null && !TextUtils.isEmpty(addressMessage.getAddress())) {
                address_id = addressMessage.getAddress_id();
                address_desc = addressMessage.getProvince() + " " + addressMessage.getCity() + " " + addressMessage.getArea() + " " + addressMessage.getAddress();
            }

            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_address = new SubmitOrderAddressAdapter(SubmitOrderActivity.this, layoutHelper, 1, null, data,saleType,isGiving) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.submit_order_address, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_address.setOnAddressClick(new SubmitOrderAddressAdapter.OnAddressClick() {
                @Override
                public void OnItemClick() {
                    if (isGiving) {
                        if ("4".equals(saleType)||"6".equals(saleType)){//采购单和提货单
                            startActivitryForResult(AddNewAddressActivity.class,new String[][]{{"isGiving","1"},{"isPurchase","1"}});
                        }else {
                            startActivitryForResult(AddNewAddressActivity.class,new String[][]{{"isGiving","1"}});
                        }
                    } else {
                        if (data.isAddress_modify_enable()){
                            if ("4".equals(saleType)||"6".equals(saleType)){
                                startActivitryForResult(ChangeAddressActivity.class, new String[][]{{"isPurchase","1"}});
                            }else {
                                startActivitryForResult(ChangeAddressActivity.class, null);
                            }
                        }
                    }
                }
            });
            adapters.add(adapter_address);
        }


        //优惠券
        boolean hasCoupon = data.isDisplay_coupon();
        if (adapters.contains(adapter_coupon)) {
            adapters.remove(adapter_coupon);
        }
        if (hasCoupon) {
            //默认选择优惠券
            for (CouponMessage couponMessage : data.getCoupons().getValids()) {
                if (couponMessage.getSelect_status()) {
                    coupon_id = couponMessage.getCouponId();
                }
            }
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_coupon = new SubmitOrderCouponAdapter(SubmitOrderActivity.this, layoutHelper, 1, null, data.getCoupons(),isGiving) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.submit_order_coupon, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_coupon.setOnCouponClick((int position) -> {
                Intent intent = new Intent(mContext, CouponChooseActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("cards", confirmOrderCoupons);
                bundle.putInt("position", position);
                intent.putExtras(bundle);
                startActivityForResult(intent, 0);
            });
            adapters.add(adapter_coupon);
        }

        //清关实名信息
        boolean hasCrossBorder = data.isHas_cross_seller();
        if (adapters.contains(adapter_cross_border)) {
            adapters.remove(adapter_cross_border);
        }
        if (hasCrossBorder) {
            CustomsClearanceMessage customsClearanceMessage = data.getCustoms_clearance();
            if (customsClearanceMessage != null && !TextUtils.isEmpty(customsClearanceMessage.getReal_name())) {
                customs_clearance_id = customsClearanceMessage.getClearance_id();
            }
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_cross_border = new SubmitOrderCrossBorderAdapter(SubmitOrderActivity.this, layoutHelper, 1, null, data) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.submit_order_cross_border, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_cross_border.setOnCrossBorderClick(new SubmitOrderCrossBorderAdapter.OnCrossBorderClick() {
                @Override
                public void OnItemClick() {
                    startActivitryForResult(CrossBorderNameSelectActivity.class, null);
                }
            });
            adapters.add(adapter_cross_border);
        }

        //保管单选项
//        if (adapters.contains(adapter_custody)) {
//            adapters.remove(adapter_custody);
//        }
//        if (!TextUtils.isEmpty(saleType)&&"4".equals(saleType)){
//            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
//            adapter_custody = new SubmitCustodyAdapter(SubmitOrderActivity.this, layoutHelper, 1, null, isCustody,firstShowCustodyDialog);
//            adapter_custody.setOnCustodyClick(new SubmitCustodyAdapter.OnCustodyClick() {
//                @Override
//                public void OnClick(String is_custody) {
//                    clickBtnName = "is_custody_btn";
//                    isCustody = is_custody;
//                    refreshOrder();
//                }
//            });
//            adapters.add(adapter_custody);
//        }

        //支付信息
        boolean hasPay = true;
        if (adapters.contains(adapter_pay)) {
            adapters.remove(adapter_pay);
        }
        if (hasPay) {

            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_pay = new SubmitOrderPayAdapter(SubmitOrderActivity.this, layoutHelper, 1, null, data, saleType) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.submit_order_pay, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_pay.setOnPayClick(new SubmitOrderPayAdapter.OnPayClick() {
                @Override
                public void OnGoldChanged(boolean isGoldSelect) {
                    gold = isGoldSelect ? "1" : "0";
                    refreshOrder();
                }

                @Override
                public void OnBalanceChanged(boolean isBalanceSelect) {
                    balance = isBalanceSelect ? "1" : "0";
                    refreshOrder();
                }

                @Override
                public void OnGZBChanged(boolean isGZBSelect) {
                    bupiao = isGZBSelect ? "1" : "0";
                    refreshOrder();
                }

                @Override
                public void OnPayWay(String payWay) {
                    payment_id = payWay;
                }
            });

            adapters.add(adapter_pay);
        }

        //商品信息
        boolean hasProducts = true;
        if (adapters.contains(adapter_products)) {
            adapters.remove(adapter_products);
        }
        if (hasProducts) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_products = new SubmitOrderProductsAdapter(SubmitOrderActivity.this, layoutHelper, data.getOrders().size(), null, data, data.getOrders(),saleType) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.view_confirm_shop_ll, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapter_products.setOnSelectFreightListener(freightType -> {
                this.freightType = String.valueOf(freightType);
                refreshOrder();
            });
            adapters.add(adapter_products);
        }


        //订单信息
        boolean hasOtherInfo = !"6".equals(saleType);
        if (adapters.contains(adapter_other_info)) {
            adapters.remove(adapter_other_info);
        }
        if (hasOtherInfo) {
            SingleLayoutHelper layoutHelper = new SingleLayoutHelper();
            adapter_other_info = new SubmitOrderOtherInfoAdapter(SubmitOrderActivity.this, layoutHelper, 1, null, data.getUpgrade_to_vip(), data.getPrice(), buy_type, saleType) {
                @Override
                public MainViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                    return new MainViewHolder(LayoutInflater.from(mContext).inflate(R.layout.submit_order_other_info, parent, false));
                }

                @Override
                public void onBindViewHolder(MainViewHolder holder, int position) {
                    super.onBindViewHolder(holder, position);
                }
            };
            adapters.add(adapter_other_info);
        }

        //清关协议签署
        if (hasCrossBorder) {
            cross_border_agreement_layout_item.setVisibility(View.VISIBLE);
            if (data.isHas_cross_seller()) {
                if (data.isClearance_agreement()) {
                    cross_border_agreement_checkbox.setChecked(true);
                } else {
                    cross_border_agreement_checkbox.setChecked(false);
                }
            }
            cross_border_agreement_txt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, BridgeActivity.class);
                    intent.putExtra("url", data.getInstructions().getCross_border_introduce());
                    intent.putExtra("title", "跨境商品用户购买须知");
                    mContext.startActivity(intent);
                }
            });
            cross_border_agreement_checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    customs_clearance_agreement = b ? "1" : "";
                }
            });

            if (data.isClearance_agreement()) {
                customs_clearance_agreement = "1";
            }
        } else {
            cross_border_agreement_layout_item.setVisibility(View.GONE);
        }

        delegateAdapter.setAdapters(adapters);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerView.scrollToPosition(0);
            }
        }, 100);

    }

    @Override
    public void confirm_order_failed(String msg) {
        showToast(msg);
    }

    @Override
    public void create_order_success(CreateOrderData data) {
        dismiss_progressDialog();
        trade_no = data.getTrade_no();
        if (data.isPay_status()) {
            payOrderSuccess();
        } else {
            PayParam payParam = data.getPay_param();
            if ("1".equals(payment_id)) {
                Runnable payRunnable = new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(SubmitOrderActivity.this);
                        Map<String, String> result = alipay.payV2(payParam.getRequest_url(), true);
                        Message msg = new Message();
                        msg.what = SDK_PAY_FLAG;
                        msg.obj = result;
                        mHandler.sendMessage(msg);
                    }
                };

                Thread payThread = new Thread(payRunnable);
                payThread.start();
            } else if ("2".equals(payment_id)) {
                iwxapi.registerApp(payParam.getApp_id());
                PayReq payReq = new PayReq();
                Config.APP_ID = payParam.getApp_id();
                payReq.appId = payParam.getApp_id();
                payReq.nonceStr = payParam.getNonce_str();
                payReq.packageValue = payParam.getWx_package();
                payReq.partnerId = payParam.getPartner_id();
                payReq.prepayId = payParam.getPrepay_id();
                payReq.timeStamp = payParam.getTimestamp();
                payReq.sign = payParam.getSign();
                payReq.signType = payParam.getSign_type();
                iwxapi.sendReq(payReq);
            }
        }

    }

    @Override
    public void create_order_failed(String msg) {
        dismiss_progressDialog();
        showToast(msg);
    }

    @Override
    public void refresh_order_success(RefreshOrderData data) {
        tvActualPrice.setText("¥ " + data.getPrice().getPay_price());
        confirmOrderCoupons = data.getCoupons();
        confirmOrderPrice = data.getPrice();
        if (adapter_coupon != null)
        adapter_coupon.refreshUI(data.getCoupons());
        adapter_products.refreshProductInfo(data.getOrders());
        this.data.setDisplay_gold(data.isDisplay_gold());
        this.data.setDisplay_balance(data.isDisplay_balance());
        this.data.setDisplay_bupiao(data.isDisplay_bupiao());
        this.data.setPrice(confirmOrderPrice);
        adapter_pay.notifyDataSetChanged();
        if (adapter_other_info != null){
            adapter_other_info.refreshUI(confirmOrderPrice);
            if ("3".equals(buy_type)) {
                adapter_other_info.refreshVipUpgradeUI(data.getUpgrade_to_vip());
            }
        }
        //刷新优惠券id
        if (data.getCoupons() != null && data.getCoupons().getValids() != null && data.getCoupons().getValids().size() > 0) {
            coupon_id = "0";
            for (CouponMessage couponMessage : data.getCoupons().getValids()) {
                if (couponMessage.getSelect_status()) {
                    coupon_id = couponMessage.getCouponId();
                }
            }
        } else {
            coupon_id = "0";
        }
    }

    @Override
    public void refresh_order_failed(String msg) {
        showToast(msg);
    }

    @Override
    public void get_trade_status_failed(String msg) {
        payOrderFailure();
    }

    @Override
    public void get_trade_status_success(TradeStatusData data) {
        if ("1".equals(data.getTrade_status())) {
            showToast("支付成功");
            payOrderSuccess();
        } else {
            payOrderFailure();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (resultCode) {
            case RESULT_CODE:
                //发票
                adapter_products.refreshInvoice(intent);
                JSONObject invoiceInfo = new JSONObject();
                Gson gson = new Gson();
                try {
                    for (ConfirmOrderOrder confirmOrderOrder : data.getOrders()) {
                        if (null != confirmOrderOrder.getSeller().getInvoiceBean()) {
                            JSONObject invoiceInfo2 = new JSONObject(gson.toJson(confirmOrderOrder.getSeller().getInvoiceBean()));
                            invoiceInfo.put(confirmOrderOrder.getSeller().getSeller_id(), invoiceInfo2);
                        }
                    }
                    invoice = invoiceInfo.toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case 103:
                //地址
                AddressBean.DataBean.ShItemsBean itemsBean = (AddressBean.DataBean.ShItemsBean) intent.getSerializableExtra("default_address");
                if (itemsBean != null) {
                    address_id = itemsBean.getSh_id();
                }
                refreshOrderMessage();
                AddressMessage addressMessage = ModelAdapterUtil.addressMessageConvert(itemsBean);
                this.data.setAddress(addressMessage);
                adapter_address.notifyDataSetChanged();
                refreshOrder();
                break;
            case 104:
                //清关实名认证信息
                CrossBorderUserMessage cross_border_user_message = (CrossBorderUserMessage) intent.getSerializableExtra("cross_order_user_message");
                if (cross_border_user_message != null) {
                    customs_clearance_id = cross_border_user_message.getSh_id();
                }
                refreshOrderMessage();
                CustomsClearanceMessage customsClearanceMessage = ModelAdapterUtil.customsClearanceMessageConvert(cross_border_user_message);
                this.data.setCustoms_clearance(customsClearanceMessage);
                adapter_cross_border.notifyDataSetChanged();
                break;
            case 109:
                //优惠券
                coupon_id = intent.getStringExtra("id");
                refreshOrder();
                break;
            case 120: {
                //赠送地址
                AddressBean.DataBean.ShItemsBean zsqitemsBean = (AddressBean.DataBean.ShItemsBean) intent.getSerializableExtra("default_address");
                if (zsqitemsBean != null) {
                    address_id = zsqitemsBean.getSh_id();
                }
                refreshOrderMessage();
                AddressMessage zsqAddressMessage = ModelAdapterUtil.addressMessageConvert(zsqitemsBean);
                this.data.setAddress(zsqAddressMessage);
                adapter_address.notifyDataSetChanged();
                refreshOrder();
            }
                break;
        }
    }

    private void refreshOrder() {
        mPresenter.refresh_order(buy_product, buy_type, coupon_id, address_id, customs_clearance_id,
                bupiao, balance, gold,saleType,freightType,relationOrderId,isCustody);
    }

    private void refreshOrderMessage() {

    }

    private void generateOrder() {
        if (TextUtils.isEmpty(address_id)) {
            showToast("请选择收货地址");
            return;
        }
        if (!UtilCollection.isAddress(address_desc.toString().trim())) {
            showToast("收货地址只允许 中文 英文 数字 - # 空格 中英文括号！");
            return;
        }

        JSONObject remarkInfo = new JSONObject();
        try {
            for (ConfirmOrderOrder confirmOrderOrder : data.getOrders()) {
                remarkInfo.put(confirmOrderOrder.getSeller().getSeller_id(), confirmOrderOrder.getSeller().getRemark());
            }
            remark = remarkInfo.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (!DoubleClickUtil.isClick(1000)) {
            return;
        }
        show_progressDialog();
        mPresenter.create_order(live_room_id, buy_product, buy_type, coupon_id, payment_id,
                bupiao, balance, data.isDisplay_gold() ? gold : "0", address_id, customs_clearance_id,
                customs_clearance_agreement, remark, invoice, charge_account,saleType,freightType,relationOrderId,isCustody);
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(SubmitOrderActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        payOrderSuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        mHandler.sendEmptyMessageDelayed(110, 100);
                    }
                    break;
                }
                case 110:
                    Toast.makeText(SubmitOrderActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    payOrderFailure();
                    break;
                default:
                    break;
            }
        }
    };

    private void payOrderSuccess(){
            startActivitry(PaySuccessActivity.class, new String[][]{{"trade_no", trade_no}, {"convert", convert}, {"sale_type",saleType},{"isGiving",isGiving?"1":"0"},{"relation_order_id",relationOrderId}});
            if ("4".equals(saleType)){
                rxBus.post(Config.PURCHASE_SUBMIT_ORDER, "");
            }else {
                if ("6".equals(saleType) && TextUtils.isEmpty(relationOrderId)){
                    rxBus.post(Config.SUBMIT_PICK_GOODS_ORDER);
                }else {
                    rxBus.post(Config.SUBMIT_ORDER, "");
                }
            }
            finish();
    }

    private void payOrderFailure(){
        if ("4".equals(saleType) || "6".equals(saleType)){
            ARouter.getInstance().build(AroutePath.PURCHASE_ORDERS_ACTIVITY)
                    .withInt("position",1)
                    .withString("from_type","purchase").navigation();
            rxBus.post(Config.PURCHASE_SUBMIT_ORDER, "");
            if (TextUtils.isEmpty(relationOrderId)) rxBus.post(Config.SUBMIT_PICK_GOODS_ORDER);
        }else {
            startActivitry(CustomerOrderActivity.class, new String[][]{{"position", "1"}});
            rxBus.post(Config.SUBMIT_ORDER, "");
        }
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(trade_no)) {
            //mPresenter.get_trade_status(trade_no);
        }
    }

}
